
package trabalhotec.gui;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.beans.PropertyVetoException;
import java.text.ParseException;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.text.MaskFormatter;
import trabalhotec.BD.DataUtil;

public class Pesquisa extends Voos{
    Vector<String> aerolst;
    JFormattedTextField dataini;
    JFormattedTextField datafim;
    JComboBox aero;
    JTable TabVol;
    JTable TabIda;
    JTextField valor2;
    static Float val;
    trabalhotec.Negocios.Voos voos = new trabalhotec.Negocios.Voos();
    trabalhotec.Negocios.Pesquisa pesq = new trabalhotec.Negocios.Pesquisa();
    public Pesquisa(){
        
        this.setTitle("Pesquisa");
        titulos = new Vector<String>();
        valores = new Vector<Vector>();
        valores = voo.listarVoo();
        
        titulos.add("Codigo");
        titulos.add("Origem");
        titulos.add("Destino");
        titulos.add("Data de partida");
        titulos.add("Data de chegada");
        titulos.add("Tempo de voo");
        titulos.add("Preco");
        titulos.add("Quantidade de Lugares vagos");
        pane = new JPanel();
        pane.setLayout(new BorderLayout());
        this.setClosable(true);
        this.setMaximizable(false);
        this.setIconifiable(true);
        this.setResizable(false);
        this.pack();
        this.getContentPane().add(pane);
    }
    public void pesqvoos(){
        pane.removeAll();
        this.setTitle("Procurar Voo");
        JLabel origem = new JLabel("Origem:");
        JLabel destino = new JLabel("Destino");
        JLabel data = new JLabel("Data");
        aerolst = voo.aeroportos();
        aerolst.add(0, null);
        Origem = new JComboBox(aerolst);
        Destino = new JComboBox(aerolst);
        try {
            Data = new JFormattedTextField(new MaskFormatter("##/##/####"));
        } catch (ParseException ex) {
            Logger.getLogger(Pesquisa.class.getName()).log(Level.SEVERE, null, ex);
        }
        pane.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        c.gridx=0;
        c.gridy=0;
        pane.add(origem,c);
        c.gridx=1;
        pane.add(Origem,c);
        c.gridx=2;
        pane.add(destino,c);
        c.gridx=3;
        pane.add(Destino,c);
        c.gridx=0;
        c.gridy=1;
        pane.add(data,c);
        c.gridx=1;
        pane.add(Data,c);
        
        JPanel botoes = new JPanel();
        botoes.setLayout(new FlowLayout());
        
        JButton Pesquisar = new JButton("Pesquisar");
        JButton LimparDados = new JButton("Limpar dados");
        JButton Sair = new JButton("Sair");
        botoes.add(Pesquisar);
        botoes.add(LimparDados);
        botoes.add(Sair);
        Pesquisar.addActionListener(new ActionListener(){
           public void actionPerformed(ActionEvent e) {
               String aux= Data.getText();
                if(!DataUtil.validaData(Data.getText())){ 
                    aux = null;
                }
                if(aux==null&&(String)Origem.getSelectedItem()==null&&(String) Destino.getSelectedItem()==null)JOptionPane.showMessageDialog(null, "Nenhum campo valido selecionado");
                else PesqResult(aux, (String) Origem.getSelectedItem(),(String) Destino.getSelectedItem());
           }
       });
       LimparDados.addActionListener(new ActionListener() {

           public void actionPerformed(ActionEvent e) {
               Data.setText(null);
               Origem.setSelectedIndex(0);
               Destino.setSelectedIndex(0);
           }
       });
       Sair.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
               try {
                   setClosed(true);
               } catch (PropertyVetoException ex) {
                   Logger.getLogger(Aeroporto.class.getName()).log(Level.SEVERE, null, ex);
               }
           }
           
       });
       
        c.gridy=2;
        c.gridwidth=3;
        c.gridx=0;
        pane.add(botoes,c);
        //this.pack();
        this.repaint();
        this.revalidate();
        
    }
    public void ResultProcura(Vector<String> titulos,Vector<Vector> ValIda, Vector<Vector> ValVolt){
        pane.removeAll();
        this.setTitle("Resultado da procura");
        pane.setLayout(new BorderLayout());
        TabIda = new JTable(ValIda, titulos);
        TabIda.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        JScrollPane paneTabIda = new JScrollPane(TabIda);
        TabVol = new JTable(ValVolt,titulos);
        TabVol.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        JScrollPane paneTabVol = new JScrollPane(TabVol);
        JPanel botoes = new JPanel();
        botoes.setLayout(new FlowLayout());
        valor2 = new JTextField(6);
        valor2.setEnabled(true);
        JButton comprar = new JButton("Comprar");
        JButton novapesq = new JButton("Nova pesquisa");
        JButton sair = new JButton("Sair");
        botoes.add(comprar);
        botoes.add(novapesq);
        botoes.add(sair);
        botoes.add(valor2);
        novapesq.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e) {
                ProcurarTrecho();
            }
            
        });
        TabIda.addMouseListener(new MouseListener(){

            public void mouseClicked(MouseEvent e) {
   
            }

            public void mousePressed(MouseEvent e) {
            }

            public void mouseReleased(MouseEvent e) {
                int selvol = TabVol.getSelectedRow();
                int selida = TabIda.getSelectedRow();
                System.out.println(selida+ " "+ selvol);
                Float valor =(Float) TabIda.getModel().getValueAt(selida, 5);
                System.out.println(valor);
                if (TabVol.getSelectedRow() == -1 )val = valor;
                else val = valor + (Float) TabVol.getModel().getValueAt(selvol, 5);
                valor2.setText(""+val);
            }

            public void mouseEntered(MouseEvent e) {
            }

            public void mouseExited(MouseEvent e) {
            }
            
        });
        TabVol.addMouseListener(new MouseListener(){

            public void mouseClicked(MouseEvent e) {
                
            }

            public void mousePressed(MouseEvent e) {
            }

            public void mouseReleased(MouseEvent e) {
                int selida = TabIda.getSelectedRow();
                int selvol = TabVol.getSelectedRow();
                System.out.println(selida+ " "+ selvol);
                Float valor = (Float) TabVol.getModel().getValueAt(selvol, 5);
                System.out.println(valor);
                if (TabIda.getSelectedRow() == -1 )val = valor;
                else val = valor + (Float) TabIda.getModel().getValueAt(selida, 5);
                valor2.setText(""+val);
            }

            public void mouseEntered(MouseEvent e) {
            }

            public void mouseExited(MouseEvent e) {
            }
            
        });
        comprar.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e) {
                int selida = TabIda.getSelectedRow();
                int selvol = TabVol.getSelectedRow();
                if(selida == -1 && selvol == -1)JOptionPane.showMessageDialog(null, "Nenhuma linha selecionada");
                else{
                    String cpf = JOptionPane.showInputDialog("Digite o CPF do cliente");
                    if(selida != -1){
                        String valorida = (String) TabIda.getModel().getValueAt(selida, 0);
                        pesq.compra(valorida, cpf);
                    }
                    if (selvol != -1 ){
                        String valorvol = (String) TabVol.getModel().getValueAt(selvol,0);
                        pesq.compra(valorvol,cpf);
                    }
                }
                JOptionPane.showMessageDialog(null, "Compra Concluida");
                try {
                    setClosed(true);
                } catch (PropertyVetoException ex) {
                    Logger.getLogger(Pesquisa.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
        });
        sair.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e) {
                try {
                    setClosed(true);
                } catch (PropertyVetoException ex) {
                    Logger.getLogger(Voos.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
        });
        pane.add(paneTabIda,BorderLayout.LINE_START);
        pane.add(paneTabVol,BorderLayout.CENTER);
        pane.add(botoes,BorderLayout.PAGE_END);
        this.pack();
        this.repaint();
        this.revalidate();
    }
    public void ProcurarTrecho(){
        pane.removeAll();
        this.setTitle("Procurar trecho");
        JLabel origem = new JLabel("Origem: ");
        JLabel destino = new JLabel("Destino:");
        JLabel datapartida = new JLabel("Data de partida");
        JLabel datachegada = new JLabel("Data de chegada");
        Vector<String> origem2 = new Vector<String>();
        origem2 = voo.aeroportos();
        Vector<String> destino2 = new Vector<String>();
        destino2 = voo.aeroportos();
        Origem = new JComboBox(origem2);
        Destino = new JComboBox(destino2);
        try {
            dataini = new JFormattedTextField(new MaskFormatter("##/##/####"));
            datafim = new JFormattedTextField(new MaskFormatter("##/##/####"));
        } catch (ParseException ex) {
            Logger.getLogger(Pesquisa.class.getName()).log(Level.SEVERE, null, ex);
        }
        pane.setLayout(new BorderLayout());
        JPanel topo = new JPanel();
        topo.setLayout(new FlowLayout());
        topo.add(origem);
        topo.add(Origem);
        topo.add(destino);
        topo.add(Destino);
        JPanel bot = new JPanel();
        bot.setLayout(new FlowLayout());
        bot.add(datapartida);
        bot.add(dataini);
        bot.add(datachegada);
        bot.add(datafim);
        JPanel botoes = new JPanel();
        botoes.setLayout(new FlowLayout());
        JButton pesqu = new JButton("Pesquisar");
        JButton Sair = new JButton("Sair");
        JButton Limpardados = new JButton("Limpar");
        botoes.add(pesqu);
        botoes.add(Sair);
        botoes.add(Limpardados);
        pesqu.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e) {
                if(DataUtil.validaData(dataini.getText()) && DataUtil.validaData(datafim.getText())){
                    if(DataUtil.obterDataDeString(dataini.getText() + " 00:00:00").compareTo(DataUtil.obterDataDeString(datafim.getText()+" 00:00:00"))>=0){
                        JOptionPane.showMessageDialog(null, "Data de partida nao pode ser maior que a data de chegada");
                    }else{
                        if(Origem.getSelectedItem().toString().equals(Destino.getSelectedItem().toString())) JOptionPane.showMessageDialog(null, "Aeroportos iguais selecionados");
                        else{
                            valores = pesq.buscatrecho((String)Origem.getSelectedItem(), (String)Destino.getSelectedItem(), dataini.getText() + " 00:00:00", datafim.getText()+" 00:00:00");
                            System.out.println(valores);
                            Vector<String> titulo = new Vector<String>();
                            titulo.add("Codigo voo");
                            titulo.add("Origem");
                            titulo.add("Destino");
                            titulo.add("Data de partida");
                            titulo.add("Data de chegada");
                            titulo.add("Preco");
                            titulo.add("Lugares vagos");
                            Vector<Vector> ValIda = pesq.buscatrecho((String)Origem.getSelectedItem(), (String)Destino.getSelectedItem(), dataini.getText() + " 00:00:00", datafim.getText()+" 00:00:00");
                            
                            Vector<Vector> ValVolt = pesq.buscavol((String)Destino.getSelectedItem(), (String)Origem.getSelectedItem(), datafim.getText()+" 00:00:00");
                            ResultProcura(titulo,/*Vector<Vector<String>>*/ ValIda, /*Vector<Vector<String>> */ValVolt);
                        }
                    }
                }else JOptionPane.showMessageDialog(null, "Datas invalidas");
            }
            
        });
        Limpardados.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e) {
                dataini.setText(null);
                datafim.setText(null);
                Origem.setSelectedIndex(0);
                Destino.setSelectedIndex(0);
            }
            
        });
        Sair.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e) {
                try {
                    setClosed(true);
                } catch (PropertyVetoException ex) {
                    Logger.getLogger(Voos.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
        });
        pane.add(topo,BorderLayout.NORTH);
        pane.add(bot,BorderLayout.CENTER);
        pane.add(botoes,BorderLayout.SOUTH);
        //this.pack();
        this.repaint();
        this.revalidate();
        
    }
    
    public void BuscarTrecho(){
        pane.removeAll();
        Listavoos(titulos,valores);
        this.setTitle("Buscar e Compra de trechos");
        tabela.setEnabled(true);
        tabela.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        JButton buscar = new JButton("Buscar");
        JButton sair = new JButton("Sair");
        JPanel botoes = new JPanel();
        botoes.add(buscar);
        botoes.add(sair);
        sair.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e) {
                try {
                    setClosed(true);
                } catch (PropertyVetoException ex) {
                    Logger.getLogger(Voos.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
        });
        buscar.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e) {
                ProcurarTrecho();
            }
            
        });
        pane.add(botoes,BorderLayout.SOUTH);
        this.repaint();
        this.revalidate();
        
    }
    public void PesqResult(String data,String origem,String destino){
        pane.removeAll();
        this.setTitle("Lista de Voos");
        valores = pesq.pesquisar(origem, destino, data);
        result = new JTable(valores,titulos);
        JScrollPane paneResult = new JScrollPane(result);
        JButton Detalhes = new JButton("Detalhes");
        JButton NovaPes = new JButton("Nova Pesquisa");
        JButton Sair = new JButton("Sair");
        pane.setLayout(new BorderLayout());
        
        Detalhes.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e) {
                int x = result.getSelectedRow();
                String item = null;
                item = (String) result.getModel().getValueAt(x,0);
                Detalhar(item);
            }
            
        });
        NovaPes.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e) {
                pesqvoos();
            }
            
        });
        Sair.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e) {
                try {
                    setClosed(true);
                } catch (PropertyVetoException ex) {
                    Logger.getLogger(Voos.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
        });
        
        pane.setLayout(new BorderLayout());
        JPanel botoes = new JPanel();
        botoes.setLayout(new FlowLayout());
        botoes.add(Detalhes);
        botoes.add(NovaPes);
        botoes.add(Sair);
        pane.add(paneResult,BorderLayout.CENTER);
        pane.add(botoes,BorderLayout.SOUTH);
        //this.pack();
        this.repaint();
        this.revalidate();
        
    }
        public void Detalhar(String item){
        pane.removeAll();
        this.setTitle("Detalhar");
        JPanel detalhesvoo = new JPanel();
        Vector<String> origem2= new Vector<String>();
        origem2.add((String) pesq.pesqResult(item).get(1));
        Vector<String> destino2 = new Vector<String>();
        destino2.add((String)pesq.pesqResult(item).get(2));
        JLabel codigo = new JLabel("Codigo:");
        JLabel origem = new JLabel("Origem:");
        JLabel destino = new JLabel("Destino:");
        JLabel data = new JLabel("Data:");
        JLabel qtdpass = new JLabel("Passagens Restantes: ");
        qtdrest = new JTextField(4);
        qtdrest.setText(pesq.pesqResult(item).get(4));
        qtdrest.setEditable(false);
        Cod = new JTextField(6);
        Cod.setText(pesq.pesqResult(item).get(0));
        Cod.setEditable(false);
        Origem = new JComboBox(origem2);
        Origem.setEditable(false);
        Origem.setEnabled(false);
        Destino = new JComboBox(destino2);
        Destino.setEnabled(false);
        Destino.setEditable(false);
        Data = new JFormattedTextField(6);
        Data.setText(pesq.pesqResult(item).get(3));
        Data.setEditable(false);
        JPanel botoes = new JPanel();
        botoes.setLayout(new FlowLayout());
        JButton Sair = new JButton("Sair");
        botoes.add(Sair);
        Sair.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e) {
                try {
                    setClosed(true);
                } catch (PropertyVetoException ex) {
                    Logger.getLogger(Pesquisa.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
        });
        detalhesvoo.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        
        detalhesvoo.add(codigo,c);
        c.gridx=1;
        detalhesvoo.add(Cod);
        c.gridx=0;
        c.gridy=1;
        detalhesvoo.add(origem,c);
        c.gridx=1;
        detalhesvoo.add(Origem,c);
        c.gridx=2;
        detalhesvoo.add(destino,c);
        c.gridx=3;
        detalhesvoo.add(Destino,c);
        c.gridx=0;
        c.gridy=2;
        detalhesvoo.add(data,c);
        c.gridx=1;
        detalhesvoo.add(Data,c);
        c.gridx=0;
        c.gridy=3;
        detalhesvoo.add(qtdpass,c);
        c.gridx=1;
        detalhesvoo.add(qtdrest,c);
        c.gridx=0;
        c.gridy=4;
        JPanel clientes = new JPanel();
        Vector<Vector<String>> valores2 = pesq.clientesVoo(item);
        Vector<String> titulos2 = new Vector<String>();
        titulos2.add("Nome");
        titulos2.add("CPF");
        titulos2.add("Email");
        titulos2.add("Sexo");
        JTable cli = new JTable(valores2,titulos2);
        clientes.setLayout(new BorderLayout());
        clientes.add(cli,BorderLayout.CENTER);
        JTabbedPane abas = new JTabbedPane();
        abas.addTab("Detalhes do voo", detalhesvoo);
        abas.addTab("Clientes do voo", clientes);
        pane.add(abas,BorderLayout.CENTER);
        pane.add(botoes,BorderLayout.SOUTH);
        this.pack();
        this.repaint();
        this.revalidate();
        
    }
    public void visualizarvoos(){
        pane.removeAll();
        this.setBounds(20, 20, 900, 400);
        Listavoos(titulos,valores);
        this.setTitle("Visualizar Voos");
        JLabel aero1 = new JLabel("Aeroporto");
        JLabel dtini = new JLabel("Data inicio");
        JLabel dtfim = new JLabel("Data fim");
        aerolst = voos.aeroportos();
        aero = new JComboBox(aerolst);
        try {
            dataini = new JFormattedTextField(new MaskFormatter("##/##/####"));
            datafim = new JFormattedTextField(new MaskFormatter("##/##/####"));
        } catch (ParseException ex) {
            Logger.getLogger(Pesquisa.class.getName()).log(Level.SEVERE, null, ex);
        }
        JPanel pesqu = new JPanel();
        pesqu.setLayout(new FlowLayout());
        pesqu.add(aero1);
        pesqu.add(aero);
        pesqu.add(dtini);
        pesqu.add(dataini);
        pesqu.add(dtfim);
        pesqu.add(datafim);
        JButton Pesquisar = new JButton("Pesquisar");
        JButton Sair = new JButton("Sair");
        pesqu.add(Pesquisar);
        pesqu.add(Sair);
        pane.add(pesqu,BorderLayout.PAGE_START);
        Sair.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
               try {
                   setClosed(true);
               } catch (PropertyVetoException ex) {
                   Logger.getLogger(Aeroporto.class.getName()).log(Level.SEVERE, null, ex);
               }
           }
           
       });
       Pesquisar.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e) {
                String dti = dataini.getText() + " 00:00:00";
                String dtf = datafim.getText()+ " 00:00:00";
                if(DataUtil.obterDataDeString(dti).compareTo(DataUtil.obterDataDeString(dtf))>=0){
                 JOptionPane.showMessageDialog(null , "Data fim nao pode ser maior que data inicio");   
                }
                else{
                if(DataUtil.validaData(dti)||DataUtil.validaData(dtf)){
                valores = pesq.buscAeros((String) aero.getSelectedItem(), dti, dtf);
                System.out.println(valores);
                if ( valores.size() == 0) JOptionPane.showMessageDialog(null, "Nao existe voos cadastrados");
                else
                visualizarvoos();
                }else JOptionPane.showMessageDialog(null, "Alguma data invalida");
            }
            }
       });
        this.pack();
        this.repaint();
        this.revalidate();
    }
}
